package cn.com.headfree.qynj.service.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.PersonalRunningWater;
import cn.com.headfree.entity.QynjDetail;
import cn.com.headfree.qynj.service.IQynjService;
import cn.com.headfree.qynj.util.AesUtil;
import cn.com.headfree.qynj.util.HttpUtils;
import cn.com.headfree.qynj.util.ShaUtil;
import cn.com.headfree.vo.ParamVo;
import cn.com.headfree.vo.PersonalRunningWaterVo;
import javassist.expr.NewArray;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("qynjService")
public class QynjServiceImpl implements IQynjService {

	private static final Logger LOG = LogManager.getLogger(QynjServiceImpl.class);

	@Value("${app_id}")
	private String appId;

	@Value("${app_secret}")
	private String appSecret;

	@Override
	public ResultData getDetailByErpNo(String idcard, String qynjxqUrl) {
		ResultData rs = new ResultData();
		JSONObject result = new JSONObject();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeStr=df.format(new Date());
		ParamVo pv=new ParamVo();
		String corpsign="";
		try {
			//测试环境
//			pv.setIdcard(AesUtil.encrypt(idcard,
//					"6b61d1926d214616ad909fc2d2c60354"));
			//生产环境
			pv.setIdcard(AesUtil.encrypt(idcard,
					appId));
			//测试环境
//			corpsign=AesUtil.encrypt("bcfd927fd8734bac8638071eb6d57679"+timeStr,
//					"6b61d1926d214616ad909fc2d2c60354");
			//生产环境
			corpsign=AesUtil.encrypt(appSecret+timeStr,
					appId);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String i=JSON.toJSONString(pv);
		System.out.println("i================="+i);
		String data = i;
		long nonce=System.currentTimeMillis();
		StringBuilder p=new StringBuilder();
		//测试环境
//		p.append("appId=6b61d1926d214616ad909fc2d2c60354")
		//生产环境
		p.append("appId="+appId)
		.append("&corpsign=").append(corpsign.replaceAll("\\+", "%2B"))
		.append("&data=").append(data.replaceAll("\\+", "%2B")).append("&method=AnnuityAccount.Info").append("&nonce=").append(nonce)
		.append("&timestamp=").append(timeStr).append("&version=1.0");

		String sign=ShaUtil.getSHA256(p.toString().toLowerCase());

		try {
			corpsign=URLEncoder.encode(corpsign,"UTF-8");
			//测试环境
//			pv.setIdcard(URLEncoder.encode(AesUtil.encrypt(idcard,
//					"6b61d1926d214616ad909fc2d2c60354")));
			//生产环境
			pv.setIdcard(URLEncoder.encode(AesUtil.encrypt(idcard,
					appId)));
			data=JSON.toJSONString(pv);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		StringBuilder p2=new StringBuilder();
		//测试环境
//		p2.append("appId=6b61d1926d214616ad909fc2d2c60354")
		//生产环境
		p2.append("appId="+appId)
		.append("&corpsign=").append(corpsign)
		.append("&data=").append(data).append("&method=AnnuityAccount.Info").append("&nonce=").append(nonce).append("&sign=").append(sign)
		.append("&timestamp=").append(timeStr).append("&version=1.0");
		try {

			System.out.println("客户端传过去的参数为:"+p2.toString());
			String jsonData=HttpUtils.http(qynjxqUrl, p2.toString());
			System.out.println("服务端返回的结果为:"+jsonData);
				LOG.info("获取到接口返回的数据为--" + jsonData);
				ObjectMapper objectMapper = new ObjectMapper();
				result = objectMapper.readValue(jsonData, new TypeReference<JSONObject>() {
				});
				LOG.info("======================result======================"+result);
				if (null != result) {
					int code=result.getInt("code");
					QynjDetail t=new QynjDetail();
					if(code==0) {
						JSONObject da = JSONObject.fromObject(result.get("data"));
						LOG.info("======================da1======================"+da);
						if (null != da) {
							da = objectMapper.readValue(da.toString(), new TypeReference<JSONObject>() {
							});
							LOG.info("======================da2======================"+da);
							t=JSON.parseObject(da.toString(),QynjDetail.class);
							String accountStatusStr="正常";
							switch(t.getAccountStatus()){
								case 0:accountStatusStr="正常";break;
								case 1:accountStatusStr="封存";break;
								case 2:accountStatusStr="禁用";break;
								case 3:accountStatusStr="支付";break;
								case 4:accountStatusStr="终止";break;
								default:accountStatusStr="正常";break;
							}
							t.setAccountStatusStr(accountStatusStr);
							String paymentStatusStr="";
								switch(t.getPaymentStatus()){
								case 0:paymentStatusStr="正常";break;
								case 1:paymentStatusStr="暂停";break;
								case 2:paymentStatusStr="终止";break;
								default:paymentStatusStr="正常";break;
							}
							t.setPaymentStatusStr(paymentStatusStr);
							LOG.info("======================解析出的对象t======================"+t);
					}
				}
				rs.setData(t);
			}else {
				rs.setSuccess(false);
				rs.setErrorMsg("查询职工企业年金账户的详细信息失败！");
			}
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查询职工企业年金账户的详细信息失败！");
			e.printStackTrace();
		}
		return rs;
	}


	@Override
	public ResultData getPersonalRunningWater(String idcard, String qynjxqUrl, String createTime, int pageSize,
			int pageNum) {
		ResultData rs = new ResultData();
		JSONObject result = new JSONObject();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeStr=df.format(new Date());
		String corpsign="";
		PersonalRunningWaterVo pv=new PersonalRunningWaterVo();
		try {
			pv.setCreateTime(createTime);
			pv.setPageSize(pageSize);
			pv.setPageNum(pageNum);
			pv.setModules("0");
			//测试环境
//			pv.setIdcard(AesUtil.encrypt(idcard,"6b61d1926d214616ad909fc2d2c60354"));
//			corpsign=AesUtil.encrypt("bcfd927fd8734bac8638071eb6d57679"+timeStr,"6b61d1926d214616ad909fc2d2c60354");
			//生产环境
			pv.setIdcard(AesUtil.encrypt(idcard,appId));
			corpsign=AesUtil.encrypt(appSecret+timeStr,appId);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String i=JSON.toJSONString(pv);
		System.out.println("i================="+i);
		String data = i;
		long nonce=System.currentTimeMillis();
		StringBuilder p=new StringBuilder();
		//测试环境
//		p.append("appId=6b61d1926d214616ad909fc2d2c60354")
		//生产环境
		p.append("appId="+appId)
		.append("&corpsign=").append(corpsign.replaceAll("\\+", "%2B"))
		.append("&data=").append(data.replaceAll("\\+", "%2B")).append("&method=AnnuityAccount.statement").append("&nonce=").append(nonce)
		.append("&timestamp=").append(timeStr).append("&version=1.0");

		String sign=ShaUtil.getSHA256(p.toString().toLowerCase());

		try {
			corpsign=URLEncoder.encode(corpsign,"UTF-8");
			//测试环境
//			pv.setIdcard(URLEncoder.encode(AesUtil.encrypt(idcard,"6b61d1926d214616ad909fc2d2c60354")));
			//生产环境
			pv.setIdcard(URLEncoder.encode(AesUtil.encrypt(idcard,appId)));
			data=JSON.toJSONString(pv);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		StringBuilder p2=new StringBuilder();
		//测试环境
//		p2.append("appId=6b61d1926d214616ad909fc2d2c60354")
		//生产环境
		p2.append("appId="+appId)
		.append("&corpsign=").append(corpsign)
		.append("&data=").append(data).append("&method=AnnuityAccount.statement").append("&nonce=").append(nonce).append("&sign=").append(sign)
		.append("&timestamp=").append(timeStr).append("&version=1.0");

		try {
					System.out.println("客户端传过去的参数为:"+p2.toString());
					String jsonData=HttpUtils.http(qynjxqUrl, p2.toString());
					System.out.println("服务端返回的结果为:"+jsonData);
						LOG.info("获取到接口返回的数据为--" + jsonData);
						ObjectMapper objectMapper = new ObjectMapper();
						result = objectMapper.readValue(jsonData, new TypeReference<JSONObject>() {});
						if (null != result) {
							int code=result.getInt("code");
							List<PersonalRunningWater> t=new ArrayList<PersonalRunningWater>();
							Map<String,Object> map=new HashMap<String,Object>();
							long total=0;
							if(code==0) {
								LOG.info("-----------------------------------------2,result为---------------------------------" + result);
								JSONObject job = JSONObject.fromObject(result.get("data"));
								total=job.getLong("total");
//								String msg=job.getString("msg");
//								System.out.println("-----------------------msg="+msg);
								LOG.info("-----------------------------------------3,数量total为---------------------------------" + total);
								JSONArray da = JSONArray.fromObject(job.get("rows"));
								if (null != da) {
									LOG.info("-----------------------------------------4,rows为---------------------------------" + da);
									t=(List<PersonalRunningWater>) JSONArray.toCollection(da,PersonalRunningWater.class);
									if(t!=null&&t.size()>0) {
										for(PersonalRunningWater prw:t) {
											String modulesStr="其他";
											switch(prw.getModules()){
												case "0":modulesStr="账户缴费";break;
												case "1":modulesStr="收益分配";break;
												case "2":modulesStr="账户支付";break;
												case "3":modulesStr="计划外转入";break;
												case "4":modulesStr="系统导入";break;
												case "5":modulesStr="其他";break;
												default:modulesStr="其他";break;
											}

											prw.setModulesStr(modulesStr);

											switch(prw.getStatementType()){
												case "0":prw.setStatementTypeStr("收入");break;
												case "1":prw.setStatementTypeStr("支出");break;
												case "2":prw.setStatementTypeStr("其他");break;
												default:prw.setStatementTypeStr("其他");break;
											}

//											prw.setStatementTypeStr("0".equals(prw.getStatementType())?"收入":"支出");
										}
									}
								}
							}
							map.put("total", total);
							map.put("rows", t);
							rs.setData(map);
						}else {
							rs.setSuccess(false);
							rs.setErrorMsg("查询职工企业年金账户的流水信息失败！");
						}
				} catch (Exception e) {
					rs.setSuccess(false);
					rs.setErrorMsg("查询职工企业年金账户的流水信息失败！");
					e.printStackTrace();
				}
				return rs;
	}

}
